#include "threadPool.h"


int exitPipe[2];

void handler(int signum)
{
    printf("receive exit signum(%d)\n", signum);
    write(exitPipe[1], "1", 1);
}

int main(int argc, char *argv[])
{
    ARGS_CHECK(argc, 2);
    //配置文件启动
    char *config_path = argv[1];
    struct server_config config;
    load_config(config_path,&config);

    pipe(exitPipe);
    if(fork())
    {
        close(exitPipe[0]);
        signal(SIGUSR1, handler);
        wait(NULL);
        printf("main process exited.\n");
        exit(EXIT_SUCCESS);
    }
    close(exitPipe[1]);
    int workerNum = config.workerNum;
    threadPool_t threadPool;
    int log_fd = open("server.log", O_RDWR|O_CREAT|O_APPEND, 0666);
    threadPoolInit(&threadPool, workerNum, log_fd);
    makeWorker(&threadPool); // create worker thread
    int sockfd = tcpInit(config.ip, config.port);
    int epfd = epoll_create(1);
    struct epoll_event readySet[1024];
    epollAdd(epfd, sockfd);
    epollAdd(epfd, exitPipe[0]);
    while(1)
    {
        int readyNum = epoll_wait(epfd, readySet, 1024, -1);
        for(int i = 0; i < readyNum; ++i)
        {
            if(readySet[i].data.fd == sockfd) // receive clien connection
            {
                int netfd = accept(sockfd, NULL, NULL);
                printf("1 clien has connected, netfd = %d\n", netfd);
                pthread_mutex_lock(&threadPool.mutex);
                enQueue(&threadPool.taskQueue, netfd);
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
            }
            else if(readySet[i].data.fd == exitPipe[0]) // receive exit signal
            {
                pthread_mutex_lock(&threadPool.mutex);
                threadPool.exitFlag = 1;
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);

                for(int j = 0; i < threadPool.workerInfo.workerNum; ++j)
                {
                    pthread_join(threadPool.workerInfo.workerArr[j], NULL);
                }
                printf("threadPool exit.\n");
                exit(EXIT_SUCCESS);
            }
        }
    }
    return 0;
}